//
//  VideoViewController.m
//  IFengNews
//
//  Created by lanou3g on 16/3/8.
//  Copyright © 2016年 徐强. All rights reserved.
//

#import "VideoViewController.h"
#import "UrlRequestManager.h"
#import "VideoListModel.h"
#import "videoTitleModel.h"
#import "videoTitleView.h"
#import "VideoTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "VideoPlayerViewController.h"
#import "RadioDetailModel.h"
#import "RadioListModel.h"
#import "RadioCollectionViewCell.h"
#import "RadioDetailViewController.h"
#import "VideoDetailViewController.h"


@interface VideoViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong)UISegmentedControl *seg;
//视频
@property (weak, nonatomic) IBOutlet UITableView *videoTableView;
//电台
@property (weak, nonatomic) IBOutlet UICollectionView *RadioCollectionView;

@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollV;


//视频所有数据
@property (nonatomic,strong)NSMutableArray *videoAllData;
//视频头视图的数据数组
@property (nonatomic,strong)NSMutableArray *videoHeaderData;

//电台大数据
@property (nonatomic,strong)NSMutableArray *radioAllData;
//电台详细数据
@property (nonatomic,strong)NSMutableArray *radioDetailData;

@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self requestData];
}
- (void)viewWillAppear:(BOOL)animated{
    self.seg.selectedSegmentIndex = self.mainScrollV.contentOffset.x / kScreenWidth;
}
- (void)initView{
    /*
     self.automaticallyAdjustsScrollViewInsets = NO;
     看这个UIViewController的这个属性你就明白了，此属性默认为YES，这样UIViewController下如果只有一个UIScollView或者其子类，那么会自动留出空白，让scollview滚动经过各种bar下面时能隐约看到内容。但是每个UIViewController只能有唯一一个UIScollView或者其子类，如果超过一个，需要将此属性设置为NO,自己去控制留白以及坐标问题。
     */
    self.automaticallyAdjustsScrollViewInsets = NO;
    //设置导航栏中间的UISegmentedControl
    UIView *titleView= [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.titleView = titleView;
    [titleView addSubview:self.seg];
    //mainScrollV设置代理，
    self.mainScrollV.delegate = self;
    //两个tableView设置代理
    self.videoTableView.delegate = self;
    self.videoTableView.dataSource = self;
    //tableViewCell的注册
    [self.videoTableView registerNib:[UINib nibWithNibName:@"VideoTableViewCell" bundle:nil] forCellReuseIdentifier:@"VideoTableViewCell"];
    //collectionView的代理
    self.RadioCollectionView.delegate = self;
    self.RadioCollectionView.dataSource = self;
    //collectionViewCell、以及头视图的注册
    [self.RadioCollectionView registerNib:[UINib nibWithNibName:@"RadioCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"RadioCollectionViewCell"];
    [self.RadioCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"RadioCollectionHeaderView"];
}
#pragma mark -请求数据
- (void)requestData{
    //视频的数据
    [UrlRequestManager requestWith:GET URL:kVideoUrl condition:nil SuccessBlock:^(id item) {
        NSArray *arr = item[@"videoSidList"];
        for (NSDictionary *dicTemp in arr) {
            videoTitleModel *model = [[videoTitleModel alloc]init];
            [model setValuesForKeysWithDictionary:dicTemp];
            [self.videoHeaderData addObject:model];
        }
        NSArray *array = item[@"videoList"];
        for (NSDictionary *dic in array) {
            VideoListModel *model = [[VideoListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.videoAllData addObject:model];
        }
        //主线程中刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.videoTableView reloadData];
        });
    } failBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    //电台的数据
    [UrlRequestManager requestWith:GET URL:kRadioUrl condition:nil SuccessBlock:^(id item) {
        NSArray *arr = item[@"cList"];
        for (NSDictionary *dic in arr)
        {
            RadioListModel *model = [[RadioListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.radioAllData addObject:model];
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dicTemp in dic[@"tList"])
            {
                RadioDetailModel *mode = [[RadioDetailModel alloc]init];
                [mode setValuesForKeysWithDictionary:dicTemp];
                [mode setValuesForKeysWithDictionary:dicTemp[@"radio"]];
                [array addObject:mode];
            }
            [self.radioDetailData addObject:array];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.RadioCollectionView reloadData];
        });
    } failBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark -mainScrollV结束减速时的操作：让UISegmentedControl与界面保持一致
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.seg.selectedSegmentIndex = self.mainScrollV.contentOffset.x / kScreenWidth;
}
#pragma mark -UISegmentedControl的点击响应事件
- (void)segAction:(UISegmentedControl *)sender{
    
    if(sender.selectedSegmentIndex == 0){
        self.mainScrollV.contentOffset = CGPointMake(0, 0);
    }else{
        self.mainScrollV.contentOffset = CGPointMake(kScreenWidth, 0);
    }
}
#pragma mark - 视频videoTableView的代理方法
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.videoAllData.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    videoTitleView *titleView = [[videoTitleView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 100) ModelArr:self.videoHeaderData];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTitleAction:)];
    [titleView addGestureRecognizer:tap];
    return titleView;
}
#pragma mark - 视频头视图中的分类点击事件
- (void)tapTitleAction:(UITapGestureRecognizer *)sender{
    
    CGPoint point = [sender locationInView:self.videoTableView];
    
    if (point.y < 100) {
        VideoDetailViewController *videoDetailVC = [[VideoDetailViewController alloc]init];
        if(point.x < kScreenWidth /4.0 ){
            //奇葩： http://c.m.163.com/nc/video/list/VAP4BFE3U/n/0-10.html
            videoDetailVC.title = @"奇葩";
            videoDetailVC.category = @"VAP4BFE3U";
            videoDetailVC.url = @"http://c.m.163.com/nc/video/list/VAP4BFE3U/n/0-10.html";
        }if (point.x >  kScreenWidth /4.0 && point.x <  kScreenWidth /2.0 ) {
            // 萌物：http://c.m.163.com/nc/video/list/VAP4BFR16/n/0-10.html
            videoDetailVC.title = @"萌物";
            videoDetailVC.category = @"VAP4BFR16";
            videoDetailVC.url = @"http://c.m.163.com/nc/video/list/VAP4BFR16/n/0-10.html";
        }if (point.x > kScreenWidth /2.0 && point.x <  kScreenWidth *3.0 /4.0 ){
            // 美女：http://c.m.163.com/nc/video/list/VAP4BG6DL/n/0-10.html
            videoDetailVC.title = @"美女";
            videoDetailVC.category = @"VAP4BG6DL";
            videoDetailVC.url = @"http://c.m.163.com/nc/video/list/VAP4BG6DL/n/0-10.html";
        }if (point.x > kScreenWidth * 3.0 /4.0){
            //精品： http://c.m.163.com/nc/video/list/VAP4BGTVD/n/0-10.html
            videoDetailVC.title = @"精品";
            videoDetailVC.category = @"VAP4BGTVD";
            videoDetailVC.url = @"http://c.m.163.com/nc/video/list/VAP4BGTVD/n/0-10.html";
        }
        [self.navigationController pushViewController:videoDetailVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 230;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VideoTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    VideoListModel *model = self.videoAllData[indexPath.row];
    //tableViewCell的赋值
    cell.title.text = model.title;
    cell.descrip.text = model.descrip;
    [cell.imV sd_setImageWithURL:[NSURL URLWithString:model.cover]];
    
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth - 40)/2.0, 54, 30, 24)];
    imageV.image = [UIImage imageNamed:@"doc_video_bottom_icon"];
    [cell.imV addSubview:imageV];
    cell.length.text = [self getTimeStrFromTime:model.length];
    cell.playCount.text = [self getPlayCountFromPlayCount:model.playCount];
    cell.replyCount.text = [NSString stringWithFormat:@"%ld",model.replyCount];
    cell.videosource.text = model.videosource;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        //视屏videoTableView的代理方法
        VideoPlayerViewController *videoPlayerVC = [[VideoPlayerViewController alloc]init];
        VideoListModel *model = self.videoAllData[indexPath.row];
        videoPlayerVC.videoUrl = model.mp4_url;
        videoPlayerVC.title = model.title;
        [self.navigationController pushViewController:videoPlayerVC animated:YES];
}
#pragma mark -私有方法
//返回播放数量
- (NSString *)getPlayCountFromPlayCount:(NSInteger )playCount{
    if (playCount >= 10000) {
        return [NSString stringWithFormat:@"%.1f万",playCount/10000.0];
    }else{
        return [NSString stringWithFormat:@"%ld",playCount];
    }
}
//返回处理过的时间字符串
- (NSString *)getTimeStrFromTime:(NSInteger)time{
    NSInteger second = time % 60;
    NSInteger minute = time / 60;
    return [NSString stringWithFormat:@"%02ld:%02ld",minute,second];
}
#pragma mark - 电台RadioCollectionView的代理方法
- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.radioDetailData[section] count];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.radioAllData.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    RadioCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RadioCollectionViewCell" forIndexPath:indexPath];
    RadioDetailModel *model = self.radioDetailData[indexPath.section][indexPath.row];
    cell.playCount.text = [NSString stringWithFormat:@"%ld",model.playCount];
    [cell.imgsrc sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
    cell.title.text = model.title;
    cell.tname.text = model.tname;
    return cell;
}
//设置header方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    RadioListModel *model = self.radioAllData[indexPath.section];
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"RadioCollectionHeaderView" forIndexPath:indexPath];
    //移除所有的子视图
    for (UIView *viewSub in view.subviews) {
        [viewSub removeFromSuperview];
    }
    view.tag = 200 + indexPath.section;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 200, 30)];
    label.text = model.cname;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [view addGestureRecognizer:tap];
    [view addSubview:label];
    return view;
}
- (void)tapAction:(UITapGestureRecognizer *)sender{
    UICollectionReusableView *view =( UICollectionReusableView *)sender.view;
    NSInteger index = view.tag - 200 ;
    RadioListModel *model = self.radioAllData[index];
    RadioDetailViewController *radioDVC = [[RadioDetailViewController alloc]init];
    radioDVC.title = model.cname;
    radioDVC.detailUrl = [NSString stringWithFormat:@"http://c.3g.163.com/nc/topicset/android/radio/%@/0-40.html",model.cid];
    [self.navigationController pushViewController:radioDVC animated:YES];
}

#pragma mark - 懒加载
- (NSMutableArray *)radioDetailData{
    if (!_radioDetailData) {
        _radioDetailData = [NSMutableArray array];
    }
    return _radioDetailData;
}
- (NSMutableArray *)radioAllData{
    if (!_radioAllData) {
        _radioAllData =[NSMutableArray array];
    }
    return _radioAllData;
}
- (NSMutableArray *)videoHeaderData{
    if (!_videoHeaderData) {
        _videoHeaderData = [NSMutableArray array];
    }
    return _videoHeaderData;
}
- (NSMutableArray *)videoAllData{
    if (!_videoAllData) {
        _videoAllData = [NSMutableArray array];
    }
    return _videoAllData;
}
- (UISegmentedControl *)seg{
    if (!_seg) {
        _seg = [[UISegmentedControl alloc]initWithItems:@[@"视频",@"电台"]];
        _seg.frame = CGRectMake(0, 0, 100, 30);
        [_seg addTarget:self action:@selector(segAction:) forControlEvents:(UIControlEventValueChanged)];
    }
    return _seg;
}

@end
